<template>
  <el-switch v-model="isDefault"
             active-color="#13ce66"
             :active-value="true"
             :inactive-value="false"
             @change="handleChange">
  </el-switch>
</template>

<script>
import axios from "axios";

export default {
  name: "DefaultShippingAddressSwitch",
  inject: ["$table"],
  props: {
    value: Object,
  },
  data () {
    return {
      isDefault: null
    }
  },
  computed: {
    addressId () {
      return this.value?.addressId;
    },
    customerId () {
      return this.value?.customerId;
    }
  },
  created () {
    this.isDefault = this.value?.isDefault;
  },
  methods: {
    refresh () {
      this.$emit("search");
      this.$table.search();
    },
    async handleChange (value) {
      let url;
      if (value) {
        url = "/basic/shippingAddress/setDefaultAddress";
      } else {
        url = "/basic/shippingAddress/removeDefaultAddress";
      }
      const { code, message } = await axios.put(url, {
        addressId: this.addressId,
        customerId: this.customerId
      })
      if (0 !== code) {
        this.$message({ message, type: "error" })
        return
      }
      this.refresh();
    }
  },
  watch: {
    value () {
      this.isDefault = this.value?.isDefault;
    }
  }
}
</script>